<template>
	<view class="inputAddress">
		<view class="wrapCalcHeight" style="width: 100%;" :style="'overflow-y:'+(showAddress==true?'hidden':'auto')">
			<view style="width: 100%;text-align: center;position: relative;">
				<map id="myMap" class="maMap" style="width: 100%;height: 230px" :latitude='latitude' :longitude='longitude' :scale='scale'
				 :markers='markers' subkey="5J6BZ-KDBCS-QOCOE-6UYIZ-X3YUS-7BFG4" :show-location="true" @tap="getLatLong" />
				<view>
					<input class="seachInput" v-model="seachKeywork" type="text" placeholder-style="color:#d9d9d9" placeholder="请输入收货地址"
					 @input="inputKework" />
				</view>
				<view class="changeAddress" @click="changeAddress()">
					<view v-if="title&&address">
						<view class="title">{{title}}</view>
						<view class="addressCss">{{address}}</view>
					</view>
					<view v-else style="height: 30px;line-height: 30px;text-align: center;">选择收货地址</view>
					<image :style="'top:'+(id?'20px':'15px')" src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/zhankai.png"></image>
				</view>
				<view v-show="showAddress" class="addressListHeight" style="width: 95%;">
					<!-- <view @click="showAddress=false" style="text-align: right;width: 100%;height: 40px;line-height: 40px;"><text style="border: 1px solid #B5B5B5;    border: 1px solid #B5B5B5;padding: 5px;border-radius: 5px;font-size: 15px;color: #383636;">收起列表</text></view> -->
					<view v-if="addressList !=''">
						<view v-for="(item,index) in addressList" :key="item.id" style="position: relative;width: 100%;text-align: left;border-bottom: 1px solid #e8e8e8;padding: 10px;color: #252426;">
							<view class="title">{{item.title}}</view>
							<view class="addressCss">{{item.address}}</view>
							<radio style="position: absolute;right: 30px;top: 20px;" :checked="item.checked" @click="selectOne(item)"></radio>
						</view>
					</view>
					<view v-else style="color: #d9d9d9;margin-top: 30px;">没有找到相关位置</view>
				</view>
			</view>

			<ul style="margin: 10px;">
				<li>
					<view class="inputAddress-name">地区</view>
					<picker mode="region" :value="region" @change="regionChange" header-text="请选择所在地区" class="area_wrapper">
						<view class="picker" v-if="!regionChangeShow">
							{{region[0]}}{{region[1]}}{{region[2]}}
						</view>
						<view class="picker" v-if="regionChangeShow">
							{{region[0]}}{{region[1]}}{{region[2]}}
						</view>
					</picker>
				</li>
				<li>
					<view class="inputAddress-name">详细地址</view>
					<input class="inputAddress-input" style="" placeholder='请填写详细地址' v-model="add_detail" />
				</li>
				<li>
					<view class="inputAddress-name">收货人</view>
					<input class="inputAddress-input" placeholder='请填写收货人姓名' v-model="consignee" />
				</li>
				<li>
					<view class="inputAddress-name">手机</view>
					<input class="inputAddress-input" placeholder='请填写收货人手机号码' v-model="phone" />
				</li>
				<li style="display: flex;align-items: center;">
					<view class="inputAddress-name">默认地址</view>
					<checkbox-group class="radio-group" style="padding-left: 20px;" @change="radioChange">
						<checkbox value="1" :checked="selectFlag" style="margin-left:10px;" />
					</checkbox-group>
				</li>
			</ul>
		</view>
		<view style="text-align: center;">
			<view class="inputAddress-btnSave" style="left: 0;" :style="'width:'+(id==''?'90%':'40%')" @click="saveAddress">保存</view>
			<view class="inputAddress-btnDel" @click="delAddress" v-if="id!=''">删除</view>
		</view>
	</view>
</template>

<script>
	export default {
  components: {

  },

  data () {
    return {
      region: ["","",""],
      consignee:"",
      phone:"",
      add_detail:"",
      postcode:"",
      is_default:0,
      id:"",//如果是修改收货地址的时候，会传入一个id
      orderId:"",  //订单号
      regionChangeShow: false,
	  
	  showAddress:false,
	  addressList:[],
	  address:"",  //地址
	  title:"",
	  seachKeywork:"",  //搜索框的关键词
	  // checked:false,
	  clickAddressaKeywork:"",
	  qqmapsdk:"",
	  latitude: 23.114509,
	  longitude: 113.403536,
	  scale:16,
	  markers: [
		  
	  ],
	  num:0  //次数累加
    }
  },
  computed: {
    selectFlag(){
      if(this.is_default==0){
        return false
      }else{
        return true
      }
    }
  },
  watch:{
	  // addressList(newVal){
		 //  if(newVal!=''){
			//   this.showAddress = true
		 //  }else{
			//   this.showAddress = false
		 //  }	
	  // }
  },
  onLoad(options){
	  this.initMap()
	//如果是修改收货地址的时候，会传入一个id
    if(options.id){
      this.id=options.id
      this.getAddressDetails(options.id)
    }else{
      this.id=''
      this.consignee=''
      this.phone=''
      this.add_detail=''
      this.postcode=''
      this.is_default=''
      this.region=["","",""]
  	  this.latitude = wx.getStorageSync("latitude")
  	  this.longitude = wx.getStorageSync("longitude")
	  this.markers[0].latitude = this.latitude
	  this.markers[0].longitude = this.longitude 
  	  // this.reverseAddress()  //如果是添加新地址，获取本地所在位置，先填充位置
    }
    this.orderId=options.orderId
  },
  methods:{
	  //点击选择收货地址 展开/隐藏
	  changeAddress(){
		  this.showAddress=!this.showAddress
		  if(this.showAddress==true && this.num==0){
			this.reverseAddress()
			this.num++
		  }
	  },
	  //选择地址列表的一个地址时触发
	  selectOne(item){
		
		this.addressList.forEach(addressItem=>{
			if(item.id == addressItem.id){
				addressItem.checked = true
				if(addressItem.checked==true){
					  this.address=item.address
					  this.title = item.title
					   //所在位置
					  this.latitude = item.location.lat
					  this.longitude = item.location.lng
					  //给小标杆赋值坐标
					  this.markers[0].latitude = item.location.lat
					  this.markers[0].longitude = item.location.lng
				}
			}else{
				addressItem.checked = false
			}
		 	 
		 })

		 
		 //显示地址列表模态款
		 this.showAddress = false
	  },
	  //监听地址输入框，输入框发生变化触发
	  inputKework(){
		  this.seachAddress(this.seachKeywork) //搜索目标地址
	  },
	  //点击地图获取经纬度，并搜出位置
	  getLatLong(e){
		  console.log(e)
		    this.latitude = e.detail.latitude
		    this.longitude = e.detail.longitude
		  	this.markers[0].latitude = e.detail.latitude
		  	this.markers[0].longitude = e.detail.longitude
			this.reverseAddress()
	  },
	  //逆地址解析 通过经纬度查询出当前地址
	  reverseAddress(type){
		 
		  this.qqmapsdk.reverseGeocoder({
			   location: this.markers[0].latitude+','+this.markers[0].longitude,
			   poi_options:"address_format=short;radius=5000",
			   success:(res)=>{
				   if(this.seachKeywork!=''){
					   this.seachAddress(this.seachKeywork)
				   }else{
					   if(this.id){
						   this.address = res.result.address
						   this.title = res.result.formatted_addresses.recommend
					   }
					   if(type!=''){
						   //如果传入的type为detail.则默认地址列表不展开
						   this.seachAddress(res.result.address,type)
						   return false
					   }
					   this.seachAddress(res.result.address)
				   }
			   }
		  })
	  },
	  //搜索附近地址  type==detail.默认地址列表不展开
	  seachAddress(keyword,type){
		     // 调用接口
			 let num = 0
			 console.log(keyword)
		     this.qqmapsdk.search({
		        keyword: keyword,  //搜索关键词
		        location: this.markers[0].latitude+','+this.markers[0].longitude,  //设置周边搜索中心点
		        success:(res)=>{ //搜索成功后的回调
				res.data.forEach(item=>{
					item.checked = false
				})
				this.addressList = res.data
				if(type=='detail'){
					this.showAddress = false
					return false
				}
				this.showAddress = true
					//多个标记点
		          // var mks = []
		          // for (var i = 0; i < res.data.length; i++) {
		          //   mks.push({ // 获取返回结果，放到mks数组中
		          //     title: res.data[i].title,
		          //     id: res.data[i].id,
		          //     latitude: res.data[i].location.lat,
		          //     longitude: res.data[i].location.lng,
		          //     iconPath:"https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/ziyuan1.png", //图标路径
		          //     width: 20,
		          //     height: 20
		          //   })
		          // }
		          //   this.markers=mks
		        },
		        fail: function (res) {
		          console.log(res);
		        },
		        
		    });
	  },
	  //初始化创建地图
	  initMap(){
		  var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
		  this.qqmapsdk = new QQMapWX({
		        key: '5J6BZ-KDBCS-QOCOE-6UYIZ-X3YUS-7BFG4'
		  });
		  console.log( this.qqmapsdk)
		  //创建个小标点
		  let marker = {	  
			  id:1,
			  iconPath:"https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/ziyuan1.png",
			  latitude: this.latitude,
			  longitude: this.longitude,
			  width:30,
			  height:30
		  }
		  this.markers.push(marker)
	  },
    radioChange(e){
      this.is_default=e.target.value[0]
    },
    regionChange(e){
      console.log(e);
      this.region=e.target.value;
      this.regionChangeShow = true;
    },
    async delAddress(){
		wx.showLoading({
			title: '删除中'
		})
      var userToken=wx.getStorageSync('userToken')
      let res=await this.$api.deleteShippingAddress({id:this.id,user_token:userToken},this.$baseUrl)
	  wx.hideLoading()
      if(res.data.level=='success'){
      		  uni.showToast({
      			icon: 'success',
      		  	title: res.data.message,
      		  	duration: 1500
      		  })
      } else{
      		  uni.showToast({
      		  	icon: 'none',
      		  	title: res.data.message,
      		  	duration: 1500
      		  })
      }
      setTimeout(()=>{
        if(res.data.level=='success'){
          wx.navigateBack({delta:1})
        }
      },1500)
    },
    async saveAddress(){
		if(!this.latitude || !this.longitude || !this.address || !this.title){
			uni.showToast({
				icon: 'success',
				title: "请选择收货地址",
				duration: 1500,
				icon:"none"
			})
			return false
		}
	 
	  wx.showLoading({
	  	title: '保存中'
	  })
      var userToken=wx.getStorageSync('userToken')
	  let params={
		  user_token:userToken,
		  consignee:this.consignee,
		  phone:this.phone,
		  province:this.region[0],
		  city:this.region[1],
		  area:this.region[2],
		  address:this.add_detail,
		  postcode:this.postcode,
		  is_default:this.is_default,
		  id:this.id,
		  lat:this.latitude,
		  lng:this.longitude
	  }
      let res=await this.$api.newShippingAddress(params,this.$baseUrl)
	  wx.hideLoading()
      if(res.data.level=='success'){
		  uni.showToast({
			icon: 'success',
		  	title: res.data.message,
		  	duration: 1500
		  })
	  } else{
		  uni.showToast({
		  	icon: 'none',
		  	title: res.data.message,
		  	duration: 1500
		  })
	  }
      setTimeout(()=>{
        if(res.data.level=='success'){
          wx.navigateBack({delta:1})
        }
      },1500)

    },
    async getAddressDetails(id){
      var userToken=wx.getStorageSync('userToken')
      let res=await this.$api.getShippingAddress({user_token:userToken,id:id},this.$baseUrl)
      let data=res.data.data
      this.consignee=data.consignee
      this.phone=data.phone
      this.add_detail=data.address
      this.postcode=data.postcode
      this.is_default=data.is_default
      this.region[0]=data.province
      this.region[1]=data.city
      this.region[2]=data.area
	  //如果之前有设地址，有经纬度赋值。否则取本地的经纬度获取当前位置
	  if(data.lat!=0 && data.lng!=0){
		  this.latitude = data.lat
		  this.longitude = data.lng
		  this.markers[0].latitude = data.lat
		  this.markers[0].longitude = data.lng
	  }else{
		  this.latitude = wx.getStorageSync("latitude")
		  this.longitude = wx.getStorageSync("longitude")
		  this.markers[0].latitude = this.latitude
		  this.markers[0].longitude = this.longitude 
	  }
	  this.reverseAddress("detail")
	  
    }
  },
 
}
</script>

<style scoped lang="scss" type="text/css">
	.addressListHeight {
		height: calc(100vh - 380px);
		margin: 10px;
		background: #fff;
		border-radius: 7px;
		overflow-y: auto;
		overflow-x: hidden;
		// width: 95%;position: absolute;left: 10px;margin-top: -9px;background-color: #f7f7f7;z-index: 10;
	}

	.wrapCalcHeight {
		height: calc(100vh - 60px);
		overflow-y: auto;
		overflow-x: hidden;
	}

	.seachInput {
		width: 90%;
		margin: 10px;
		padding: 5px;
		border: 1px solid #dadada;
		position: absolute;
		top: 0px;
		background: #fff;
		height: 25px;
		line-height: 25px;
		border-radius: 5px;
		font-size: 14px;
	}

	.picker {
		text-indent: 20px;
	}

	.changeAddress {
		margin: 10px;
		border: 1px solid #ececec;
		background-color: #fff;
		border-radius: 5px;
		color: #2CB85F;
		padding: 10px;
		position: relative;
		text-align: left;

		image {
			width: 25px;
			height: 25px;
			vertical-align: middle;
			position: absolute;
			right: 15px;
			top: 20px;
		}
	}

	.title {
		width: 85%;
		font-size: 16px;
		color: #333333;
	}

	.addressCss {
		width: 85%;
		font-size: 14px;
		margin-top: 5px;
		color: #BFBFBF;
	}

	@import "../../common/css/mixin.scss";

	.inputAddress {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background: #f5f5f5;

		.inputAddress-name {
			width: 80px;
		}

		li {
			display: flex;
			height: 50px;
			background-color: #fff;
			border-top: 1px solid #eee;
			color: black;

			.area_wrapper {
				width: calc(100% - 90px);
				height: 100%;

				view {
					margin: 10px 10px;
					height: 30px;
					line-height: 30px;
					width: calc(100% - 20px);
					@include ellipsis(1);
				}
			}
		}

		&-name {
			width: 70px;
			line-height: 50px;
			text-indent: 10px;
			// color:white;
		}

		&-input {
			flex: 1;
			height: 30px;
			margin: 10px 10px;
			line-height: 30px;
			padding-left: 20px;
		}

		.inputAddress-btnSave {
			width: 40%;
			line-height: 40px;
			background-color: #2CB85F;
			border-radius: 3px;
			text-align: center;
			color: #fff;
			margin: 0px 5% 0px;
			position: absolute;
			bottom: 10px;
			border-radius: 25px;
			// left: 0;
		}

		&-btnDel {
			@extend .inputAddress-btnSave;
			background-color: #ff3236 !important;
			color: #FFFFFF;
			margin: 0px 5% 0px !important;
			right: 0 !important;
		}
	}
</style>
